﻿using System;
using System.IO;
using System.Web;

namespace easy_ccms.core
{
    /// <summary>
    /// Mail parser.
    /// </summary>
    public class MailTemplateParser
    {
        /// <summary>
        /// Loaded template file.
        /// </summary>
        private string _template;

        /// <summary>
        /// Loads the template file to memory.
        /// </summary>
        /// <param name="file">The file.</param>
        public void LoadTemplate(string file)
        {
            if (File.Exists(HttpContext.Current.Server.MapPath(file)))

                using (var sr = new StreamReader(HttpContext.Current.Server.MapPath(file)))
                {
                    //This allows you to do one Read operation.
                    _template = sr.ReadToEnd();
                }
        }

        /// <summary>
        /// Determines whether [is valid file] [the specified file path].
        /// </summary>
        /// <param name="filePath">The file path.</param>
        /// <returns>
        ///   <c>true</c> if [is valid file] [the specified file path]; otherwise, <c>false</c>.
        /// </returns>
        private Boolean IsValidFile(String filePath)
        {
            return File.Exists(filePath);
        }

        /// <summary>
        /// Parses the text into template.
        /// 
        /// </summary>
        /// <param name="holderName">Name of the holder in square brackets e.g.: [Header].</param>
        /// <param name="newContent">The new content.</param>
        public void ParseText(string holderName, string newContent)
        {
            if (_template.Length != 0)
                _template = _template.Replace("[" + holderName + "]", newContent);
        }

        /// <summary>
        /// Gets the template.
        /// </summary>
        /// <returns>String or null.</returns>
        public String GetTemplate()
        {
            return (_template.Length != 0) ? _template : null;
        }
    }
}